package service

import (
	"errors"
	"gopkg.in/gomail.v2"
	"guns-go/global"
	"guns-go/model/request"
)

func SendMail(sendMailParam *request.SendMailParam) error {

	err := checkParamByEmail(sendMailParam)

	if err != nil {
		return err
	}

	m := gomail.NewMessage()

	//这种方式可以添加别名，即“XX官方”
	m.SetHeader("From", m.FormatAddress(global.GVA_CONFIG.Email.From, "guns-go"))
	//发送给多个用户
	m.SetHeader("To", sendMailParam.To)
	//设置邮件主题
	m.SetHeader("Subject", sendMailParam.Title)
	//设置邮件正文
	m.SetBody("text/html", sendMailParam.Content)

	err = global.GVA_EMAIL.DialAndSend(m)

	if err != nil {
		return err
	}

	return nil
}
func SendHtmlMail(sendMailParam *request.SendMailParam) error {

	err := checkParamByEmail(sendMailParam)

	if err != nil {
		return err
	}

	m := gomail.NewMessage()

	m.SetHeader("From", m.FormatAddress(global.GVA_CONFIG.Email.From, "guns-go"))
	m.SetHeader("To", sendMailParam.To)
	m.SetAddressHeader("Cc", global.GVA_CONFIG.Email.From, global.GVA_CONFIG.Email.Nickname)
	m.SetHeader("Subject", sendMailParam.Title)
	m.SetBody("text/html", sendMailParam.Content)

	err = global.GVA_EMAIL.DialAndSend(m)

	if err != nil {
		return err
	}

	return nil
}

func checkParamByEmail(sendMailParam *request.SendMailParam) error {

	to := sendMailParam.To
	if to == "" {
		return errors.New("收件人为空，请检查to参数")
	}

	title := sendMailParam.Title
	if title == "" {
		return errors.New("标题为空，请检查title参数")
	}

	content := sendMailParam.Content
	if content == "" {
		return errors.New("内容为空，请检查content参数")
	}

	return nil
}
